import { app, ipcMain, shell } from 'electron';
import { Service } from '../types';
import { setIpcReplier, logger, store, setAutoStart } from '../utils';

export class IpcService extends Service {
    run() {
        ipcMain.on('app-close', this.onAppClose.bind(this));
        ipcMain.on('set-text', this.setText.bind(this));
        this.setIpcRequest();
    }


    private async onAppClose() {
        app.quit();
    }

    private async setText(e, data) {
        logger.info(data);
        const { scrollText, fontSize, speed, color, shadowColor, autoStart,fade } = data;
        this.app.context.scrollText = scrollText;
        this.app.context.fontSize = fontSize;
        this.app.context.speed = speed;
        this.app.context.color = color;
        this.app.context.shadowColor = shadowColor;
        this.app.context.autoStart = autoStart;
        this.app.context.fade = fade;
        store.set("scrollText", scrollText);
        store.set("fontSize", fontSize);
        store.set("speed", speed);
        store.set("color", color);
        store.set("shadowColor", shadowColor);
        store.set("autoStart", autoStart);
        store.set("fade", fade);
        if (data.autoStart === true) {
            setAutoStart(true);
        } else if (data.autoStart === false) {
            setAutoStart(false);
        }

        this.app.windowService.getWindow()?.webContents?.send('get-new-set')
    }

    private async getSeting() {
        logger.info(this.app.context);
        const { scrollText, fontSize, speed, color, shadowColor, autoStart, fade } = this.app.context;
        const data = { scrollText, fontSize, speed, color, shadowColor, autoStart, fade }
        return Promise.resolve({
            data,
            success: true
        })
    }
    setIpcRequest() {
        const { http } = this.app;
        setIpcReplier("get-random-word", http.getRandomBg.bind(http))
        setIpcReplier("get-scroll-text-setting", this.getSeting.bind(this))
    }
}
